﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponentsDx.Browsers;
using Wydatki.WRK.Praca.DataSets;
using ProgNetComponentsDx.Options;

namespace Wydatki.WRK.Praca
{
    public partial class FormWrkVatz : MyBaseSqlCeGridForm
    {
        private int Rok;
        private bool pauseEvents;

        public FormWrkVatz()
            : this(Settings.RokPodatkowy == null ? DateTime.Now.Year : Settings.RokPodatkowy.Value)
        {

        }

        public FormWrkVatz(int rok)
            : base()
        {
            InitializeComponent();
            WydatkiGlobals.Events.DefPrevMonth(this.rep_WRK_VATZ_DATA_NABYCIA_PRAW);

            this.Text += " [Rok: " + rok + "]";
            this.selectDataProvider1.GetSettings(this).Parameters["ROK"].Value = rok;
            Rok = rok;
        }

        protected override void FinishEdit()
        {
            base.FinishEdit();
            DateTime dt;
            foreach (DataRow r in wrkVatzDataSet.WRK_VATZ.Rows)
            {
                if (r.CanRead() && r["WRK_VATZ_DATA_WYSTAWIENIA"].IsNotNull())
                {
                    dt = r["WRK_VATZ_DATA_WYSTAWIENIA"].AsDateTime(DateTime.MinValue);
                    if (dt.Year != r["WRK_VATZ_ROK"].AsInt())
                        r["WRK_VATZ_ROK"] = dt.Year;
                }
            }
        }
        protected override bool Save()
        {
            WrkVatzDataSet ds = wrkVatzDataSet.Copy() as WrkVatzDataSet;

            bool res  = base.Save();
            if (res)
            {
                if (!SetupIpmortTools.AddVatzToKpir(wrkVatzDataSet))
                    this.ShowDxWarningDialog("Błąd dodawania faktur do Księgi  Przychodów i Rozchodów");

                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work.AddVatzToWydatki))
                    Tools.WydatkiTools.ProcessNewWydatki(ds);

                this.GetRecords();
            }
            return res;
        }

        protected override bool ValidateAll()
        {
            bool res = base.ValidateAll();
            if (res)
                res = ValidateRok();
            if (res)
            {

                DataRow[] rows = wrkVatzDataSet.WRK_VATZ.Select("WRK_VATZ_ROK <> " + Rok);
                if (rows.Length > 0)
                {
                    string msg = "Nie wszystkie wpisy są z roku " + Rok;
                    DialogResult dlg = this.ShowDxYNQuestionDialog(msg + "\nCzy chcesz zapisac dane?");
                    if (dlg == System.Windows.Forms.DialogResult.No)
                    {
                        res = false;
                        ValidationMessage = msg;
                        
                        foreach (DataRow r in rows)
                            r.SetColumnError("WRK_VATZ_DATA_WYSTAWIENIA", "Zły rok.");
                    }
                }
            }
            return res;
        }
        private bool ValidateRok()
        {
            bool res = true;
             DataRow[] rows = wrkVatzDataSet.WRK_VATZ.Select();
             List<int> invalid = new List<int>();
             int rok;
             Browser b = browserProvider1.GetBrowser(Init.InitFormBrowserNames.Glowna.LataPodatkowe);
             foreach (DataRow r in rows)
             {
                 rok = r["WRK_VATZ_ROK"].AsInt();
                 if (!b.IsValid(false, rok))
                 {
                     invalid.AddIfNotExist(rok);
                     r.SetColumnError("WRK_VATZ_DATA_WYSTAWIENIA", "Brak roku podatkowego.");
                 }
             }
             if (invalid.Count > 0)
             {
                 res = false;
                 foreach (int i in invalid)
                     ValidationMessage = ValidationMessage.AppendLine("Brak roku podatkowego " + i);
             }
            
             return res;
        }
        private void repItemNumer_Settings_AdditionalBrowserValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            e.Cancel = true;
            FinishEdit();
            DataRow r = gvMain.GetFocusedDataRow();
            if (r == null)
            {
                gvMain.AddNewRow();
                gvMain.UpdateCurrentRow();
                r = gvMain.GetFocusedDataRow();
            }
            if (r != null)
            {
                int i = e.NewValue.AsInt(-1);
                if (i > -1)
                {
                    SetupIpmortTools.AddVatzFromDef(wrkVatzDataSet, i, r);
                }
            }
        }

        private void bbiSaveAs_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FinishEdit();
            DataRow r = gvMain.GetFocusedDataRow();
            if (r != null)
            {
                SetupIpmortTools.SaveVatzAsDef(r);
            }
        }

        private void gvMain_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Value.IsNotNull() && !pauseEvents)
            {
                DevExpress.XtraGrid.Columns.GridColumn[] cols = new DevExpress.XtraGrid.Columns.GridColumn[]{
                    colWRK_VATZ_DATA_WYSTAWIENIA,
                    colWRK_VATZ_DATA_NABYCIA_PRAW,
                    colWRK_VATZ_DATA_WPLYWU
                };
                if (cols.Contains(e.Column))
                {
                    foreach (DevExpress.XtraGrid.Columns.GridColumn c in cols)
                    {
                        if (c != e.Column)
                        {
                            if (gvMain.GetRowCellValue(e.RowHandle, c).IsNull())
                            {
                                pauseEvents = true;
                                gvMain.SetRowCellValue(e.RowHandle, c, e.Value);
                                pauseEvents = false;
                            }
                        }
                    }
                }
            }
        }

        private void gvMain_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            DataRow r = gvMain.GetDataRow(e.RowHandle);
            if (r != null)
                r["DODAJ_DO_KPIR"] = true;
        }
    }
}
